using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.SqlClient ; 
using System.Windows.Forms;
using Colorprj.Common;
using Colorprj.Masters ;
namespace Colorprj
{
    public partial class frmPur : Form
    {
        ProductMasterData pmd = new ProductMasterData();
        Purchase.PurchaseManager pm = new Purchase.PurchaseManager();

        BuyerManager bm = new BuyerManager();
        SubProductManager spm = new SubProductManager(); 
        public frmPur()
        {
            InitializeComponent();
        }

        private void frmPur_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'colorPrjDataSet5.Party' table. You can move, or remove it, as needed.
            //this.partyTableAdapter.Fill(this.colorPrjDataSet5.Party);

            cboParty.DataSource = bm.GetAllBuyers(2).Tables[0];
            cboParty.DisplayMember = "BuyerName";
            cboParty.ValueMember  = "BuyerId";
            SubProduct.DataSource = spm.GetAllProducts().Tables[0] ;
            SubProduct.DisplayMember = "subProductName";
            SubProduct.ValueMember = "subProductId"; 

            //DataSet dsTables = new DataSet();
            //dsTables =pmd.GetMultipleTableDataset() ;
            //dsTables.Tables[0].TableName = "Product";
            //dsTables.Tables[1].TableName = "subProduct";

            //// set up ParentBS and ChildBS and filteredChildBS
            //parentBS.DataSource = dsTables;
            //parentBS.DataMember = "Product";

            //childBS.DataSource = dsTables;
            //childBS.DataMember = "subProduct";

            //filteredChildBS.DataSource = dsTables;
            //filteredChildBS.DataMember = "subProduct";

            //// bind the regionComboBoxColumn to the parentBS
            //this.Product.DataSource = parentBS;
            //this.Product.DisplayMember = "productName";
            //this.Product.ValueMember = "productId";

            //// bind the territoryComboBoxColumn to the childBS
            //this.SubProduct.DataSource = childBS;
            //this.SubProduct.DisplayMember = "subproductName";
            //this.SubProduct.ValueMember = "subproductId";


        }

        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dataGridView2_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            string headerText =dataGridView2.Columns[e.ColumnIndex].HeaderText;

            
            if (headerText.Equals("Sub-prd"))
            {
                if (string.IsNullOrEmpty(e.FormattedValue.ToString()))
                {
                    dataGridView2.Rows[e.RowIndex].ErrorText =
                        "Sub Product must not be empty";
                    e.Cancel = true;
                }

                if (IsDuplicate(e.FormattedValue.ToString()) && dataGridView2.Rows[e.RowIndex].Cells["PurdetId"].Value ==null )
                {
                    dataGridView2.Rows[e.RowIndex].ErrorText =
                                "Sub Product Allready Exist";
                    e.Cancel = true;

                } 
            }
          
            //if (headerText.Equals("Qty"))
            //{
            //    if (Convert.ToDouble(e.FormattedValue) <= 0) {
            //        dataGridView2.Rows[e.RowIndex].ErrorText =
            //            "Qty must not be 0";
            //        e.Cancel = true;
            //    }
            //}
        }

        private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView2.Rows[e.RowIndex].ErrorText = String.Empty;

        }

       // private void dataGridView2_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
       // {
       //     if (this.dataGridView2.Columns["Column2"].Index ==
       //e.ColumnIndex && e.RowIndex >= 0)
       //     {
       //         Rectangle newRect = new Rectangle(e.CellBounds.X + 1,
       //             e.CellBounds.Y + 1, e.CellBounds.Width - 4,
       //             e.CellBounds.Height - 4);

       //         using (
       //             Brush gridBrush = new SolidBrush(this.dataGridView2.GridColor),
       //             backColorBrush = new SolidBrush(e.CellStyle.BackColor))
       //         {
       //             using (Pen gridLinePen = new Pen(gridBrush))
       //             {
       //                 // Erase the cell.
       //                 e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

       //                 // Draw the grid lines (only the right and bottom lines;
       //                 // DataGridView takes care of the others).
       //                 e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
       //                     e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
       //                     e.CellBounds.Bottom - 1);
       //                 e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
       //                     e.CellBounds.Top, e.CellBounds.Right - 1,
       //                     e.CellBounds.Bottom);

       //                 // Draw the inset highlight box.
       //                 e.Graphics.DrawRectangle(Pens.Blue, newRect);

       //                 // Draw the text content of the cell, ignoring alignment.
       //                 if (e.Value != null)
       //                 {
       //                     e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
       //                         Brushes.Crimson, e.CellBounds.X + 2,
       //                         e.CellBounds.Y + 2, StringFormat.GenericDefault);
       //                 }
       //                 e.Handled = true;
       //             }
       //         }
       //     }

       // }

        private void dataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            ////if (this.dataGridView2.CurrentCell.ColumnIndex == SubProduct.Index)
            ////{
            ////    DataGridViewComboBoxEditingControl control = e.Control as DataGridViewComboBoxEditingControl;
            ////    BindingSource bs = control.DataSource as BindingSource;
            ////    if (bs != null)
            ////    {
            ////        // set the filteredChildBS as the DataSource of the editing control
            ////        (e.Control as ComboBox).DataSource = filteredChildBS;

            ////        object regionvalue = this.dataGridView2.Rows[this.dataGridView2.CurrentCell.RowIndex].Cells[Product.Index].Value;
            ////        if (regionvalue == DBNull.Value || regionvalue == null)
            ////        {
            ////            filteredChildBS.Filter = "Productid=-1";
            ////        }
            ////        else
            ////        {
            ////            filteredChildBS.Filter = "Productid=" + regionvalue.ToString();
            ////        }
            ////        // set the SelectedValue property of the editing control
            ////        if (this.dataGridView2.CurrentCell.Value != DBNull.Value && this.dataGridView2.CurrentCell.Value != null)
            ////        {
            ////            control.SelectedValue = this.dataGridView2.CurrentCell.Value;
            ////        }
            ////    }
            ////}

        }

        private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {


            ////if (e.ColumnIndex == Product.Index)
            ////{
            ////    // clear the cell value of the territory column in the same row
            ////    //if (this.dataGridView2.DataSource.GetType() == typeof(DataTable))
            ////    //{
            ////    //    this.dataGridView2.Rows[e.RowIndex].Cells[SubProduct.Index].Value = DBNull.Value;
            ////    //}
            ////    //else
            ////    //{
            ////    if (e.RowIndex >= 0 )
            ////        this.dataGridView2.Rows[e.RowIndex].Cells[SubProduct.Index].Value = null;

            ////    //}
            ////}


            if (e.RowIndex >= 0 && e.ColumnIndex == 0)
            {

                int myval = Convert.ToInt16(this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
                this.dataGridView2.Rows[e.RowIndex].Cells["Rate"].Value = pm.GetSubProductById(myval).PurRate; 

            }

            //if (e.RowIndex >=0 && e.ColumnIndex == Column3.Index)
            //{
            //    // clear the cell value of the territory column in the same row
            //    if (this.dataGridView2.DataSource.GetType() == typeof(DataTable))
            //    {
            //        this.dataGridView2.Rows[e.RowIndex].Cells[Column5.Index].Value = DBNull.Value;
            //    }
            //    else
            //    {
            //        this.dataGridView2.Rows[e.RowIndex].Cells[Column5.Index].Value = null;
            //    }
            //}
        }
        private bool IsDuplicate(string  spvalue) {
            bool retval = false ;
            int rowCnt = 0;
            System.Collections.Hashtable hash = new System.Collections.Hashtable();

            for (rowCnt = 0; rowCnt < dataGridView2.RowCount-1; rowCnt++)
            {
                String SubproductId = dataGridView2["Subproduct", rowCnt].FormattedValue.ToString()  ;
                if (hash.Contains(spvalue))
                {
                    retval = true;
                    break;
                }
                else
                {
                    hash.Add(SubproductId, SubproductId);
                }

            }
            return retval;
        }
        private Purchase.PurchaseHeadEntity getFormData()
        {
            Purchase.PurchaseHeadEntity phEntity = new Colorprj.Purchase.PurchaseHeadEntity();
            phEntity.PartyId = Convert.ToInt16(cboParty.SelectedValue);
            phEntity.PurNo = txtPurNo.Text;
            phEntity.PurDate = dtPurDate.Value;

            phEntity.CenVat = Utility.getDblVal(txtCenVat.Text);
            phEntity.CST = Utility.getDblVal(txtCst.Text);
            phEntity.Ecess = Utility.getDblVal(txtEcess .Text);
            phEntity.Total  = Utility.getDblVal(txtTotal.Text);
            phEntity.STotal = Utility.getDblVal(txtStotal.Text);
            phEntity.GTotal = Utility.getDblVal(txtGtotal.Text);
            phEntity.Scharge = Utility.getDblVal(txtSCharge.Text);
            phEntity.SHEcess = Utility.getDblVal(txtSheCess.Text);
            phEntity.Freight = Utility.getDblVal(txtFreight.Text);  

            if (!txtPurHeadId.Text.Trim().Equals(""))
            {
                phEntity.PurHeadId = Convert.ToInt16(txtPurHeadId.Text);
            }

            List<Purchase.PurDetailEntity> pdEntityList = new List<Colorprj.Purchase.PurDetailEntity>();
            int rowCnt = 0;
            for (rowCnt = 0; rowCnt < dataGridView2.RowCount; rowCnt++)
            {
                //int prdId = Convert.ToInt16(dataGridView2["Product", rowCnt].Value);
                //int subPrdId = Convert.ToInt16(dataGridView2["Subproduct", rowCnt].Value);
                //int qty = Convert.ToInt16(dataGridView2["Qty", rowCnt].Value);
                //if (qty > 0)
                //{
                    Purchase.PurDetailEntity pdEntity = new Colorprj.Purchase.PurDetailEntity();
                   //pdEntity.ProductId = Convert.ToInt16(dataGridView2["Product", rowCnt].Value);
                    pdEntity.Qty = Utility.getDblVal(dataGridView2["Qty", rowCnt].Value);
                    pdEntity.OldQty = Utility.getDblVal(dataGridView2["OldQty", rowCnt].Value);
                    pdEntity.Rate = Utility.getDblVal(dataGridView2["Rate", rowCnt].Value);
                    pdEntity.Amount = Utility.getDblVal(dataGridView2["Amount", rowCnt].Value);
                    pdEntity.SubproductId = Convert.ToInt16(dataGridView2["Subproduct", rowCnt].Value);
                    pdEntity.PurDetailId = Convert.ToInt16(dataGridView2["PurDetId", rowCnt].Value);
                    if (pdEntity.Qty > 0 || pdEntity.OldQty>0)
                    {
                        pdEntityList.Add(pdEntity);
                    }
                //}
            }
            phEntity.PurDetailList = pdEntityList;
            return phEntity;
        }


        private void button1_Click(object sender, EventArgs e)
        {
            //Purchase.PurchaseHeadEntity phEntity = getFormData(); 
            //Purchase.PurchaseManager pm = new Colorprj.Purchase.PurchaseManager();
            //pm.AddPurchase(phEntity);
            //ClearForm();
        }

        private void button2_Click(object sender, EventArgs e)
        {
           
          

            PurSearch ps = new PurSearch();
            if (ps.ShowDialog() == DialogResult.OK)
            {
               
                int  purId = Convert.ToInt16( ps.ItemToRead);
                

                 Purchase.PurchaseHeadEntity phEntity= pm.GetPurchase(purId);
                 txtPurHeadId.Text = purId.ToString() ;
                 txtPurNo.Text = phEntity.PurNo;
                 dtPurDate.Value = phEntity.PurDate ;
                cboParty.SelectedValue = phEntity.PartyId  ;
                txtFreight.Text = phEntity.Freight.ToString();
                txtCst.Text = phEntity.CST.ToString();
                txtEcess .Text = phEntity.Ecess.ToString();
                txtSCharge .Text = phEntity.Scharge.ToString();
                txtSheCess .Text = phEntity.SHEcess.ToString();
                txtCenVat.Text = phEntity.CenVat.ToString();
                txtStotal.Text = phEntity.STotal.ToString();
                txtTotal.Text = phEntity.Total.ToString();
                txtGtotal.Text = phEntity.GTotal .ToString();  



                 dataGridView2.RowCount = phEntity.PurDetailList.Count+1 ;
                 int row = 0;
                 foreach (Purchase.PurDetailEntity pdEntity in phEntity.PurDetailList) {

                     dataGridView2["Product", row].Value = pdEntity.ProductId;
                     dataGridView2["SubProduct", row].Value = pdEntity.SubproductId;
                     dataGridView2["Qty", row].Value = pdEntity.Qty ;
                     dataGridView2["OldQty", row].Value = pdEntity.Qty;
                     dataGridView2["Rate", row].Value = pdEntity.Rate ;
                     dataGridView2["Amount", row].Value = pdEntity.Amount;
                     dataGridView2["PurDetId", row].Value = pdEntity.PurDetailId;
                     row++;
                 
                 }

                 btnSave.Enabled = false;
                 btnUpdate.Enabled = true; 
            }

            
            
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ClearForm(this.Controls );
        }

        //private void ClearForm() {

        //    btnSave.Enabled = true;
        //    btnUpdate.Enabled = false;
        //    //this.dataGridView2.Rows.Clear();
        //    txtPurHeadId.Text = "";
        //    txtTotal.Text = ""; 
        //    //txtPurNo.Text = "";
        //   // cboParty.SelectedIndex = -1;
        //    //foreach (Control c in Form.ControlCollection )
        //    //{
        //    //    if (c is TextBox)
        //    //    {
        //    //        ((TextBox)c).Text = ((TextBox)c).Text + ((TextBox)c).Name + "\n";
        //    //    }
        //    //}
        //    Control.ControlCollection coll = this.Controls ;
        //    //List<ComboBox> list33 = GetControlsOfType<ComboBox>(coll);
        //    foreach (Control c in coll)
        //    {
        //        //if (c != null)
        //        //    Console.WriteLine(c.Text, "Index numb: " + coll.GetChildIndex(c, false));
        //        if (c is TextBox) c.Text = string.Empty;
        //        if (c is DataGridView) {((DataGridView) c).Rows.Clear(); }
        //        if (c is ComboBox)
        //        {
        //            ((ComboBox)c).SelectedIndex = -1;
        //        }
        //    }


            


        //}

        public void ClearForm(Control.ControlCollection coll)
        {
            // Control.ControlCollection coll = this.Controls;
            foreach (Control c in coll)
            {
                if (c.HasChildren) ClearForm(c.Controls);
                if (c is TextBox) c.Text = string.Empty;
                if (c is DataGridView) { ((DataGridView)c).Rows.Clear(); }
                if (c is ComboBox)
                {
                    ((ComboBox)c).SelectedIndex = -1;
                }
            }
            txtTotal.Text = "";
            txtStotal.Text = "";
            txtGtotal.Text = "";
            btnSave.Enabled =true ;
            btnUpdate.Enabled = false;
        }
        private void dataGridView2_CellLeave(object sender, DataGridViewCellEventArgs e)
        {

            ////if (e.ColumnIndex == Product.Index) {
            ////    filteredChildBS.Filter = "Productid=-1";
            ////    //SubProduct.DataSource = filteredChildBS; ; ; 
            ////    //DataGridViewCell   col55 = this.dataGridView2.CurrentCell.  ;

            ////    DataGridViewComboBoxCell dgcb = (DataGridViewComboBoxCell)dataGridView2[e.ColumnIndex+1, e.RowIndex];
            ////    dgcb.DataSource = filteredChildBS;

            ////   // dataGridView2[1, e.RowIndex].Value = -1;
            ////    //col55.Value = null; 
            ////}

            //if (this.dataGridView2.CurrentCell.ColumnIndex == Product.Index)
            //{
            //    DataGridViewComboBoxEditingControl control = e.Control as DataGridViewComboBoxEditingControl;
            //    BindingSource bs = control.DataSource as BindingSource;
            //    if (bs != null)
            //    {
            //        // set the filteredChildBS as the DataSource of the editing control
            //        (e.Control as ComboBox).DataSource = filteredChildBS;

            //        object regionvalue = this.dataGridView2.Rows[this.dataGridView2.CurrentCell.RowIndex].Cells[Product.Index].Value;
            //        if (regionvalue == DBNull.Value || regionvalue == null)
            //        {
            //            filteredChildBS.Filter = "Productid=-1";
            //        }
            //        else
            //        {
            //            filteredChildBS.Filter = "Productid=" + regionvalue.ToString();
            //        }
            //        // set the SelectedValue property of the editing control
            //        if (this.dataGridView2.CurrentCell.Value != DBNull.Value && this.dataGridView2.CurrentCell.Value != null)
            //        {
            //            control.SelectedValue = this.dataGridView2.CurrentCell.Value;
            //        }
            //    }
            //}


            dataGridView2["Amount", e.RowIndex].Value = Convert.ToDecimal(dataGridView2["Qty", e.RowIndex].Value) * Convert.ToDecimal(dataGridView2["Rate", e.RowIndex].Value);

            //if (dataGridView2[0, e.RowIndex].Value != null && dataGridView2[1, e.RowIndex].Value != null && dataGridView2[2, e.RowIndex].Value != null)
            //{

                // string aa = dataGridView2[1, e.RowIndex].Value.ToString() ;
                dataGridView2.AllowUserToAddRows = true;

            //}
            //else { dataGridView2.AllowUserToAddRows = false; }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            //try
            //{

            //    Purchase.PurchaseHeadEntity phEntity = getFormData();
            //    Purchase.PurchaseManager pm = new Colorprj.Purchase.PurchaseManager();
            //    pm.UpdPurchase(phEntity);

            //    ClearForm();
            //}
            //catch (Exception  ex) {

            //    MessageBox.Show(ex.Message);  
            
            //}

        }

        private void dataGridView2_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            

            if (dataGridView2[0, e.RowIndex].Value != null && dataGridView2[1, e.RowIndex].Value != null && Convert.ToInt16(dataGridView2[2, e.RowIndex].Value) != 0 && Convert.ToDecimal(dataGridView2[3, e.RowIndex].Value) != 0)
            {

                // string aa = dataGridView2[1, e.RowIndex].Value.ToString() ;
                if (dataGridView2.RowCount==e.RowIndex )
                dataGridView2.AllowUserToAddRows = true;
                
            }
            else { 
                if (dataGridView2.RowCount !=1) 
                dataGridView2.AllowUserToAddRows = false; 
            }
        }

        private void dataGridView2_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView2["Amount", e.RowIndex].Value = Convert.ToDecimal (dataGridView2["Qty", e.RowIndex].Value) * Convert.ToDecimal(dataGridView2["Rate", e.RowIndex].Value);

            if (dataGridView2.Rows.Count > 0)
            {
                txtTotal.Text = Total().ToString("F2");
                doTotal(); 
            }

        }
        private double Total()
        {
            double tot = 0;
            int i = 0;
            for (i = 0; i < dataGridView2.Rows.Count; i++)
            {
                tot = tot + Utility.getDblVal(dataGridView2.Rows[i].Cells["Amount"].Value);
            }
            doTotal();
            return tot;
        }

        private void txtCenVat_TextChanged(object sender, EventArgs e)
        {
            doTotal();
        }

        private void doTotal() {

            txtStotal.Text = Convert.ToString(Utility.getDblVal(txtTotal.Text) + Utility.getDblVal(txtCenVat.Text) + Utility.getDblVal(txtEcess.Text) + Utility.getDblVal(txtSheCess.Text));
            txtGtotal.Text = Convert.ToString(Utility.getDblVal(txtStotal.Text) + Utility.getDblVal(txtCst.Text) + Utility.getDblVal(txtSCharge.Text) + Utility.getDblVal(txtFreight.Text));    
        }
        private void NumericKeyPress(System.Object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            TextBox tb =(TextBox) sender;


            if (!(char.IsDigit(e.KeyChar) | char.IsControl(e.KeyChar) | (e.KeyChar.Equals('.') & tb.Text.IndexOf(".") < 0)))
            
            {
                e.Handled = true;

            }


            if ((tb.SelectionStart > tb.Text.Length - 2 & tb.Text.IndexOf(".") >= 0 & tb.Text.IndexOf(".") + 3 == tb.Text.Length))
            {
                e.Handled = true;

            }


            if (e.Handled == false & tb.Text.Length == 0)
            {
                tb.Text = "" + e.KeyChar;

                e.Handled = true;

                tb.SelectionStart = 2;

            }

        }


        private void TextKeyPress(System.Object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (!(char.IsLetter(e.KeyChar) | char.IsControl(e.KeyChar)))
                e.Handled = true;

        }


        private void NumericLeave(System.Object sender, System.EventArgs e)
        {
            TextBox tb = (TextBox)sender;

            if (tb.Text.Length == 0)
                tb.Text = "0.00";
          
        }

        private void txtEcess_KeyPress(object sender, KeyPressEventArgs e)
        {

        }
        


        private void txtSheCess_TextChanged(object sender, EventArgs e)
        {
            doTotal();
        }

        private void txtEcess_TextChanged(object sender, EventArgs e)
        {
            doTotal();
        }

        private void txtCst_TextChanged(object sender, EventArgs e)
        {
            doTotal();
        }

        private void txtSCharge_TextChanged(object sender, EventArgs e)
        {
            doTotal();
        }

        private void txtFreight_TextChanged(object sender, EventArgs e)
        {
            doTotal();
        }

        private void txtGtotal_TextChanged(object sender, EventArgs e)
        {

        }

        private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
        }

        private void dataGridView2_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            
        }

        private void cboParty_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            PurSearch ps = new PurSearch();
            if (ps.ShowDialog() == DialogResult.OK)
            {

                int purId = Convert.ToInt16(ps.ItemToRead);


                Purchase.PurchaseHeadEntity phEntity = pm.GetPurchase(purId);
                txtPurHeadId.Text = purId.ToString();
                txtPurNo.Text = phEntity.PurNo;
                dtPurDate.Value = phEntity.PurDate;
                cboParty.SelectedValue = phEntity.PartyId;
                txtFreight.Text = phEntity.Freight.ToString();
                txtCst.Text = phEntity.CST.ToString();
                txtEcess.Text = phEntity.Ecess.ToString();
                txtSCharge.Text = phEntity.Scharge.ToString();
                txtSheCess.Text = phEntity.SHEcess.ToString();
                txtCenVat.Text = phEntity.CenVat.ToString();
                txtStotal.Text = phEntity.STotal.ToString();
                txtTotal.Text = phEntity.Total.ToString();
                txtGtotal.Text = phEntity.GTotal.ToString();



                dataGridView2.RowCount = phEntity.PurDetailList.Count + 1;
                int row = 0;
                foreach (Purchase.PurDetailEntity pdEntity in phEntity.PurDetailList)
                {

                    //dataGridView2["Product", row].Value = pdEntity.ProductId;
                    dataGridView2["SubProduct", row].Value = pdEntity.SubproductId;
                    dataGridView2["SubProduct", row].ReadOnly = true;
                    dataGridView2["Qty", row].Value = pdEntity.Qty;
                    dataGridView2["OldQty", row].Value = pdEntity.Qty;
                    dataGridView2["Rate", row].Value = pdEntity.Rate;
                    dataGridView2["Amount", row].Value = pdEntity.Amount;
                    dataGridView2["PurDetId", row].Value = pdEntity.PurDetailId;
                    row++;

                }

                btnSave.Enabled = false;
                btnUpdate.Enabled = true;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try {
            Purchase.PurchaseHeadEntity phEntity = getFormData();
            if (phEntity.PurDetailList.Count == 0) {
                throw new Exception("Please enter Product detail "); 
            
            }
            Purchase.PurchaseManager pm = new Colorprj.Purchase.PurchaseManager();
            pm.AddPurchase(phEntity);
            ClearForm(this.Controls);
        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.Message);

        }
        }

        private void btnUpdate_Click_1(object sender, EventArgs e)
        {
            try
            {

                Purchase.PurchaseHeadEntity phEntity = getFormData();
                Purchase.PurchaseManager pm = new Colorprj.Purchase.PurchaseManager();
                pm.UpdPurchase(phEntity);
                MessageBox.Show ("Record successfully Saved ");
                ClearForm(this.Controls);
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);

            }
        }

        private void dataGridView2_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (Utility.getDblVal(dataGridView2.Rows[e.RowIndex].Cells["Qty"].Value) <= 0 && dataGridView2.Rows[e.RowIndex].Cells["PurDetId"].Value == null)
            {
                dataGridView2.Rows[e.RowIndex].ErrorText =
                       "Qty must not be 0";
                e.Cancel = true;
            } 
        }

        private void btnCancel_Click_1(object sender, EventArgs e)
        {
            ClearForm(this.Controls);
        }


    }
}